<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail" ref="ruleForm">
        <a-row>
          <a-col :span="24">
            <a-form-item label="优惠券标题" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                v-decorator="['title', validatorRules.title]"
                placeholder="请输入优惠券标题（有图片则显示图片）：无门槛50元优惠券 | 单品最高减2000元"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="图片" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-image-upload :isMultiple="formDisabled" v-decorator="['icon']"></j-image-upload>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="用途" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                type="list"
                v-decorator="['used', validatorRules.used]"
                :trigger-change="true"
                dictCode="coupon_used"
                placeholder="请选择可用于：1店铺优惠券 新人店铺券  3商品优惠券  4类目优惠券  5平台优惠券 6新人平台券"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                type="list"
                v-decorator="['type', validatorRules.type]"
                :trigger-change="true"
                dictCode="coupon_type"
                placeholder="请选择1满减券 2叠加满减券 3无门槛券（需要限制大小）"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="兑换所需积分" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number
                v-decorator="['redeemPoints', validatorRules.redeemPoints]"
                placeholder="请输入兑换所需积分"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="特价商品使用" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                type="list"
                v-decorator="['withSpecial', validatorRules.withSpecial]"
                :trigger-change="true"
                dictCode="coupon_special"
                placeholder="请选择1可用于特价商品 2不能  默认不能(商品优惠卷除外)"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="满金额" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number
                v-decorator="['withAmount', validatorRules.withAmount]"
                placeholder="请输入满多少金额"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="减金" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number
                @change="jianjiChange"
                v-decorator="['usedAmount', validatorRules.usedAmount]"
                placeholder="请输入减金"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="配额" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number
                v-decorator="['quota', validatorRules.quota]"
                placeholder="请输入配额：发券数量　0:无限"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <!--<a-col :span="24">
            <a-form-item label="已领取数量" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="['takeCount']" placeholder="请输入已领取的优惠券数量" style="width: 100%" disabled/>
            </a-form-item>
          </a-col>-->
          <a-col :span="24">
            <a-form-item label="使用说明" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['rulesExplain']" placeholder="请输入使用规则说明"></a-input>
            </a-form-item>
          </a-col>
          <!--<a-col :span="24">
            <a-form-item label="已使用数量" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="['usedCount', validatorRules.usedCount]" placeholder="请输入已使用的优惠券数量" style="width: 100%"/>
            </a-form-item>
          </a-col>-->
          <!--时间二选一-->
          <a-col :span="24">
            <a-form-item
              label="使用时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              extra="时间选择和有效天数必须填写一个且不能全部填写"
            >
              <a-tabs :activeKey="tabKey" @change="callback" >
                <a-tab-pane key="one" tab="时间范围">
                  <a-form-item label="使用开始时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <j-date
                      placeholder="请选择使用开始时间"
                      v-decorator="['validStartTime']"
                      :trigger-change="true"
                      :showTime="false"
                      dateFormat="YYYY-MM-DD"
                      style="width: 100%"
                      :getCalendarContainer="getModalAsContainer"
                    />
                  </a-form-item>
                  <a-form-item label="使用结束时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <j-date
                      placeholder="请选择使用结束时间"
                      v-decorator="['validEndTime']"
                      :trigger-change="true"
                      dateFormat="YYYY-MM-DD"
                      :showTime="false"
                      style="width: 100%"
                      :getCalendarContainer="getModalAsContainer"
                      @change="timeChange"
                    />
                  </a-form-item>
                </a-tab-pane>
                <a-tab-pane key="two" tab="有效天数" force-render>
                  <a-form-item label="有效天数" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-input-number
                      v-decorator="['validDays']"
                      placeholder="请输入自领取之日起有效天数"
                      style="width: 100%"
                    />
                  </a-form-item>
                </a-tab-pane>
              </a-tabs>
            </a-form-item>
          </a-col>

          <!--<a-col :span="24">
            <a-form-item label="使用开始时间" :labelCol="labelCol" :wrapperCol="wrapperCol" extra="时间选择和有效天数必须填写一个且不能全部填写">
              <j-date placeholder="请选择使用开始时间" v-decorator="['validStartTime']" :trigger-change="true" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="使用结束时间" :labelCol="labelCol" :wrapperCol="wrapperCol" extra="时间选择和有效天数必须填写一个且不能全部填写">
              <j-date placeholder="请选择使用结束时间" v-decorator="['validEndTime']" :trigger-change="true" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="有效天数" :labelCol="labelCol" :wrapperCol="wrapperCol" extra="时间选择和有效天数必须填写一个且不能全部填写">
&lt;!&ndash;              <a-input-number v-decorator="['validDays', validatorRules.validDays]" placeholder="请输入自领取之日起有效天数" style="width: 100%"/>&ndash;&gt;
              <a-input-number v-decorator="['validDays']" placeholder="请输入自领取之日起有效天数" style="width: 100%"/>
            </a-form-item>
          </a-col>-->
          <a-col :span="24">
            <a-form-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                type="list"
                v-decorator="['status', validatorRules.status]"
                :trigger-change="true"
                dictCode="coupon_status"
                placeholder="请选择1生效 2失效 3已结束"
              />
            </a-form-item>
          </a-col>
          <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import pick from 'lodash.pick'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import JDate from '@/components/jeecg/JDate'
import JImageUpload from '@/components/jeecg/JImageUpload'
import JDictSelectTag from '@/components/dict/JDictSelectTag'

/*校验减金不能大于满金额*/
let withAmountCheck = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入满多少金额!'))
  } else {
    this.$refs.ruleForm.validateField('withAmount')

    callback()
  }
}
let usedAmountCheck = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入减金!'))
  } else if (value > this.manjin) {
    callback(new Error('减金不能大于满金！'))
  } else {
    callback()
  }
}

export default {
  name: 'CouponForm',
  components: {
    JFormContainer,
    JDate,
    JImageUpload,
    JDictSelectTag,
  },
  props: {
    //流程表单data
    formData: {
      type: Object,
      default: () => {},
      required: false,
    },
    //表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false,
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    return {
      manjin: '',
      tabKey: 'one',
      form: this.$form.createForm(this),
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
        title: {
          rules: [
            { required: true, message: '请输入优惠券标题（有图片则显示图片）：无门槛50元优惠券 | 单品最高减2000元!' },
          ],
        },
        used: {
          rules: [
            {
              required: true,
              message: '请输入可用于：1店铺优惠券 新人店铺券  3商品优惠券  4类目优惠券  5平台优惠券 6新人平台券!',
            },
          ],
        },
        type: {
          rules: [{ required: true, message: '请输入1满减券 2叠加满减券 3无门槛券（需要限制大小）!' }],
        },
        redeemPoints: {
          rules: [{ required: true, message: '请输入兑换所需积分!' }],
        },
        withSpecial: {
          rules: [{ required: true, message: '请输入1可用于特价商品 2不能  默认不能(商品优惠卷除外)!' }],
        },
        withAmount: {
          rules: [
            { required: true, message: '请输入满多少金额!' },
            /* {
                validator: (rule, value, callback) => {
                  this.manjin = value
                },
              },*/
          ],
        },
        usedAmount: {
          rules: [
            { required: true, message: '请输入减金!' },
            /* {
                validator: (rule, value, callback) => {
                  console.log('value',value)
                  if (value>this.manjin){
                    callback(new Error("减金不能大于满金!"));
                  }else {
                    callback()
                  }
                },
              },*/
          ],
        },
        quota: {
          rules: [{ required: true, message: '请输入配额：发券数量　0:无限!' }],
        },
        takeCount: {
          rules: [{ required: true, message: '请输入已领取的优惠券数量!' }],
        },
        usedCount: {
          rules: [{ required: true, message: '请输入已使用的优惠券数量!' }],
        },
        validDays: {
          rules: [{ required: true, message: '请输入自领取之日起有效天数!' }],
        },
        status: {
          rules: [{ required: true, message: '请输入1生效 2失效 3已结束!' }],
        },
      },
      url: {
        add: '/activity/coupon/add',
        edit: '/activity/coupon/edit',
        queryById: '/activity/coupon/queryById',
      },
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    },
  },
  created() {
    //如果是流程中表单，则需要加载流程表单data
    this.showFlowData()
  },
  methods: {
    timeChange(e) {
      console.log(e)
      /*console.log(e)
        this.form.getFieldDecorator('validEndTime', {
          getValueFromEvent:()=>{
            e+' 23.59.59'
          }
        })*/
    },
    jianjiChange(e) {
      console.log(e)
    },
    //时间弹框防止遮挡
    getModalAsContainer(node) {
      return document.querySelector('.j-modal-box .ant-modal-content')
    },
    add() {
      this.edit({})
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(
          pick(
            this.model,
            'title',
            'icon',
            'used',
            'type',
            'withSpecial',
            'redeemPoints',
            'withAmount',
            'usedAmount',
            'quota',
            'rulesExplain',
            'validStartTime',
            'validEndTime',
            'validDays',
            'status'
          )
        )
      })
    },
    //渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result)
          }
        })
      }
    },
    submitForm() {
      console.log(111)
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (values.validStartTime && values.validEndTime && values.validDays) {
          this.$message.error('时间范围选择和有效天数只能填写一种')
          return false
        } else if (values.usedAmount > values.withAmount) {
          this.$message.error('减金不能大于满金!')
          return false
        } else if (!values.validStartTime && values.validEndTime && values.validDays) {
          this.$message.error('时间范围选择和有效天数只能填写一种')
          return false
        } else if (values.validStartTime && !values.validEndTime && values.validDays) {
          this.$message.error('时间范围选择和有效天数只能填写一种')
          return false
        } else if (!values.validStartTime && !values.validEndTime && !values.validDays) {
          this.$message.error('时间范围选择和有效天数必须填写一种')
          return false
        } else if (!values.validStartTime && values.validEndTime && !values.validDays) {
          this.$message.error('请选择开始日期')
          return false
        } else if (values.validStartTime && !values.validEndTime && !values.validDays) {
          this.$message.error('请选择结束日期')
          return false
        } else {
          if (!err) {
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            if (!this.model.id) {
              httpurl += this.url.add
              method = 'post'
            } else {
              httpurl += this.url.edit
              method = 'put'
            }
            /*if(this.model.validStartTime && this.model.validEndTime && this.model.validDays==''){

            }*/
            /*if (that.tabKey=='one') {
              values.validEndTime += ' 23:59:59'
              values.validDays = ""
            } else if(that.tabKey=='two' && !values.validDays){
              values.validEndTime += ' 23:59:59'
              values.validDays = ""
            }else{
              values.validStartTime = ''
              values.validEndTime = ''
            }*/

            let formData = Object.assign(this.model, values)
            if (formData.validEndTime){
              formData.validEndTime += ' 23:59:59'
            }
            console.log('表单提交数据', formData)
            // debugger
            httpAction(httpurl, formData, method)
              .then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.$emit('ok')
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.confirmLoading = false
              })
          }
        }
      })
    },
    popupCallback(row) {
      this.form.setFieldsValue(
        pick(
          row,
          'title',
          'icon',
          'used',
          'type',
          'withSpecial',
          'withAmount',
          'redeemPoints',
          'usedAmount',
          'quota',
          'rulesExplain',
          'validStartTime',
          'validEndTime',
          'validDays',
          'status'
        )
      )
    },

    //tab切换
    callback(key) {
      this.tabKey = key
    },
  },
}
</script>